/* The object of the current event which is edited */
var eventObject;

/**
 * Prepares the form for editing an event.
 *  
 * @param {String} id of the event which should be edited
 */
function editEvent(id) {
    eventObject = storage.findEvent(id);
    putDataInForm(eventObject);
    showForm();
    setFormEditMode(true);
}

/**
 * Puts the data of the given event in the form. 
 *  
 * @param {type} event
 */
function putDataInForm(event) {
    document.getElementById("title").value = event.title;
    document.getElementById("location").value = event.location;
    document.getElementById("mail").value = event.organizer;

    document.getElementById(event.status).selected = "true";

    /* checks weather it´s an allday event or not */
    if (event.allday === "1") {
        allDayEvent(true);
        document.getElementById("allDay").checked = true;
    } else {
        allDayEvent(false);
    }

    /* put start date in form */
    var start = event.start.split("T");
    document.getElementById("startDate").value = start[0];
    document.getElementById("startTime").value = start[1];

    /* put end date in form */
    var end = event.end.split("T");
    document.getElementById("endDate").value = end[0];
    document.getElementById("endTime").value = end[1];

    document.getElementById("webpage").value = event.webpage;
    
    // select all categories of event
    for (var i = 0; i < event.categories.length; i++) {
        document.getElementById("category" + event.categories[i].name).selected = "true";
    }
    
    document.getElementById("imgURL").innerHTML = event.imageurl;
    
}

/**
 * Edits the function which is called when sending the form. 
 * 
 * @param {boolean} edit defines if the form is used to create a new event or to edit a event
 */
function setFormEditMode(edit) {
    var form = document.getElementById("form");

    // IMPORTANT add "return false;" to prevent default action of form !!!
    if (edit) {
        document.getElementById("formTitle").innerHTML = "Edit";
        
        form.onsubmit = function () {
            editData();
            return false;
        };
    } else {
        document.getElementById("formTitle").innerHTML = "New";
        form.onsubmit = function () {
            submitData();
            return false;
        };
    }

}


/**
 * Request to change the event in the form on the server. 
 */
function editData() {
    var request = new XMLHttpRequest();
    request.open("POST", URL_START, true);
    
    
    
    request.onreadystatechange = function () {
        alertError(request, "update event data");
        if (request.readyState === 4 && (request.status === 200 || request.status === 0)) {
            initialize();
            
            // remove unused events
            var tmpUnused = [];
            for (var i = 0, max = eventObject.categories.length; i < max; i++) {
                tmpUnused[i] = eventObject.categories[i].id;
            }
            removeUnusedCategories(eventObject.id, categoryInArray(tmpUnused, getSelectedCategories()));
            
            // add new categories
            var tmpNew = categoryInArray(getSelectedCategories(), tmpUnused);
            for (var i = 0, max = tmpNew.length; i < max; i++) {
                mapCategoryToEvent(eventObject.id, tmpNew[i]);
            }
            
            var img = document.getElementById("imgURL");
            if (img.innerHTML) {
                if (img.innerHTML !== eventObject.imageurl) {
                    if (eventObject.imageurl) {
                        removeUnusedImage(eventObject.id);
                    }
                    mapImageToEvent(eventObject.id, document.getElementById("image").files[0]);
                } 
            } else {
                if (eventObject.imageurl) {
                    removeUnusedImage(eventObject.id);
                }
            }
            
            hideForm();
        }
    };

    var formData = new FormData();

    /* add information for action on server */
    formData.append("user", USER);
    formData.append("action", "update");
    formData.append("format", "json");

    formData.append("id", eventObject.id);
    request.send(appendFormInformation(formData));
}

/**
 * Removes the image from the given element.
 * 
 * @param {String} eventId
 */
function removeUnusedImage(eventId) {
    var rmRequest = new XMLHttpRequest();

    rmRequest.open("POST", URL_START, true);
    rmRequest.onreadystatechange = function () {
        alertError(rmRequest, "remove image from event");
        if (rmRequest.readyState === 4 && (rmRequest.status === 200 || rmRequest.status === 0)) {
            initialize();

        } else if (rmRequest.status !== 200) {
            alert("Error: " + rmRequest.status);
        }
    };

    var formData = new FormData();
    formData.append("user", USER);
    formData.append("action", "delete-image");
    formData.append("format", "json");

    formData.append("id", eventId);
    rmRequest.send(formData);
}


/**
 * Removes unused categories from a given event. 
 * 
 * @param {type} eventId id of the event
 * @param {String[]} unused array with ids of unused categories
 */
function removeUnusedCategories(eventId, unused) {
    for (var i = 0, max = unused.length; i < max; i++) {
        var rmRequest = new XMLHttpRequest();
        
        rmRequest.open("POST", URL_START, true);
        rmRequest.onreadystatechange = function () {
            alertError(rmRequest, "remove unused categories");
            if (rmRequest.readyState === 4 && (rmRequest.status === 200 || rmRequest.status === 0)) {
                initialize();

            } else if (rmRequest.status !== 200) {
                alert("Error: " + rmRequest.status);
            }
        };

        var formData = new FormData();
        formData.append("user", USER);
        formData.append("action", "remove-category");
        formData.append("format", "json");

        formData.append("event", eventId);
        formData.append("category", unused[i]);

        rmRequest.send(formData);
    }
}

/**
 * Checks if the elements in the first array are contained in the second array.
 * If the Element is not contained in the second array its id is added to a 
 * temporary array. 
 * At the end the array with all element ids which are not contained in the second
 * array is returned; 
 * 
 * @param {String[]} fa First array array with ids
 * @param {String[]} sa Second array array with ids
 * @returns {String[]} difference array with element ids not contained in sa
 */
function categoryInArray(fa, sa) {
    var difference = [];
    for (var first = 0, firstMax = fa.length; first < firstMax; first++) {
        var contained = false;
        // search for matching elements in sa
        for (var second = 0, secondMax = sa.length; second < secondMax; second++) {
            if (fa[first] === sa[second]) {
                contained = true;
                break;
            }
        }
        if (!contained) {
            difference[difference.length] = fa[first];
            //alert("not contained: " + storage.findCategory(fa[first]).name);
        }
    }
    
    return difference;
}


